# -*- coding: UTF-8 -*-
import time

from pydblite import Base

import conf

# 1-active,2-inactive,3-warn
STATE_MAPPING = {
    "STATE_CELL_RF_OPEN": 1,
    "STARTING": 2,
    "ACTIVED": 2,
    "CLOSED": 2,
    "STOPPING": 3,
    "PHY_CRASHED": 3,
    "SYNC_FAIL": 3
}

# 其他消息表
table = Base('response_msg', save_to_file=False)
msg_table = table.create(('addr', 'TEXT'), ('code', 'TEXT'), ('msg', 'TEXT'), ('create_time', 'TEXT'),
                         mode='override')
# 心跳信息表
h_table = Base('heart_msg', save_to_file=False)
heart_table = h_table.create(('addr', 'TEXT'), ('code', 'TEXT default 101'), ('state', 'TEXT'),
                             ('freq', 'TEXT'), ('temp', 'TEXT'), ('gps', 'TEXT'), ('mode', 'TEXT'), ('msg', 'TEXT'),
                             ('create_time', 'TEXT'), mode='override')
# 默认地址
default_addr = '0.0.0.0'


def set_msg(msg):
    data_arr = msg.split(' ')
    code = data_arr[0]
    create_time = str(int(time.time()))
    expire_time = str(int(time.time()) - 90)
    # heart
    if code == '101':
        state_code = 3
        for item in data_arr:
            if item.find("STATE") == 0:
                state_code = get_value(item)
                state_code = STATE_MAPPING.get(state_code, 3)
        global heart_table
        all_item = heart_table(addr=default_addr)
        for item in all_item:
            heart_table.delete(item)
        heart_table.insert(addr=default_addr, code=code, state=state_code, msg=msg,
                           create_time=create_time)
        return heart_table()[-1]
    # 清理90秒所有的消息
    global msg_table
    expire_item = (msg_table("create_time") <= expire_time) & (msg_table('addr') == default_addr)
    for item in expire_item:
        msg_table.delete(item)
    msg_table.insert(addr=default_addr, code=code, msg=msg, create_time=create_time)
    return msg_table()[-1]


def clear_msg(addr):
    global msg_table
    all_item = msg_table(addr=addr)
    for item in all_item:
        msg_table.delete(item)


def get_value(val):
    return val[val.find('[') + 1:val.find(']')]


def get_item_val(msg, item_name):
    item_idx = msg.find(item_name)
    if item_idx < 0:
        return ''
    msg = msg[item_idx + 1:]
    return msg[msg.find('[') + 1:msg.find(']')]


def get_msg_by_code(code, create_time):
    global msg_table
    create_time_str = str(create_time)
    all_item = []
    for item in (msg_table("create_time") >= create_time_str) & (msg_table("addr") == default_addr) & (
            msg_table("code") == code):
        all_item.append(item.get('msg'))
    if len(all_item) > 0:
        return all_item[-1]
    return None


def get_msg_by_code_rule_msg(code, rule_msg, create_time):
    global msg_table
    create_time_str = str(create_time)
    all_item = []
    for item in (msg_table("create_time") >= create_time_str) & (msg_table("addr") == default_addr) & (
            msg_table("code") == code):
        all_item.append(item)
    if len(all_item) > 0:
        last_msg = None
        for item in all_item:
            if item.get('msg', '').find(rule_msg) != -1:
                last_msg = item.get('msg')
        return last_msg
    return None


def get_heart_status():
    global heart_table
    heart_items = heart_table(addr=default_addr)
    if len(heart_items) > 0:
        response = heart_items[-1]
        if response:
            time_stamp = int(response.get('create_time', 0))
            if int(time.time()) - time_stamp > (conf.lte_beat_heart_time + 2):
                return 3
            return response.get('state', 3)
    return 3


if __name__ == '__main__':
    msg = '109 CmdAck B1-91  SetRfPara RESULT[SUCCESS] INFO[Success set RF para]'
    set_msg(msg)
